package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.ApprovalDetailAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.ApprovalBean;
import com.lzx.iteam.bean.ApprovalData;
import com.lzx.iteam.bean.DateBean;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.MyListView;
import com.lzx.iteam.widget.RoundImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.baidu.location.b.g.i;
import static com.lzx.iteam.util.DateUtil.getAppYandMandD;

/**
 * Created by Megan on 16/4/7.
 */
public class ApprovalDetailActivity extends MyBaseActivity implements View.OnClickListener{


    @FindViewById(id = R.id.approval_detaill_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.approval_detail_lv)
    private MyListView mApLv;
    @FindViewById(id = R.id.approval_detaill_tv_title)
    private TextView mTvTitle;
    @FindViewById(id = R.id.approval_head_tv_name)
    private TextView mTvName;
    @FindViewById(id = R.id.approval_head_iv)
    private RoundImageView mIvAvatar;
    @FindViewById(id = R.id.approval_head_tv_state)
    private TextView mTvStatus;
    @FindViewById(id = R.id.approval_head_iv_state)
    private ImageView mIvStatus;
    @FindViewById(id = R.id.ll_leave_type)
    private LinearLayout mLayoutLeaveType;
    @FindViewById(id = R.id.tv_leave_type)
    private TextView mTvLeaveType;
    @FindViewById(id = R.id.ll_traval_place)
    private LinearLayout mLayoutTraval;
    @FindViewById(id = R.id.tv_traval_place)
    private TextView mTvTravalPlace;
    @FindViewById(id = R.id.tv_start_time_title)
    private TextView mTvStartTimeTitle;
    @FindViewById(id = R.id.tv_start_time)
    private TextView mTvStartTime;
    @FindViewById(id = R.id.ll_end_time)
    private LinearLayout mLayoutEnd;
    @FindViewById(id = R.id.tv_end_time)
    private TextView mTvEndTime;
    @FindViewById(id = R.id.ll_days)
    private LinearLayout mLayoutDays;
    @FindViewById(id = R.id.tv_days)
    private TextView mTvDays;
    @FindViewById(id = R.id.tv_days_title)
    private TextView mTvDayTitle;
    @FindViewById(id = R.id.tv_reason_title)
    private TextView mTvReasonTitle;
    @FindViewById(id = R.id.tv_reason)
    private TextView mTvReason;
    @FindViewById(id = R.id.approval_ll_action)
    private LinearLayout mLayoutAction;
    @FindViewById(id = R.id.approval_botton_agree)
    private LinearLayout mLayoutAgree;
    @FindViewById(id = R.id.approval_botton_refuse)
    private LinearLayout mLayoutRefuse;
    @FindViewById(id = R.id.approval_botton_cancel)
    private LinearLayout mLayoutCancel;
    @FindViewById(id = R.id.approval_detail_content)
    private LinearLayout mLayoutContent;



    private ApprovalData mApprovalData ;
    private List<ApprovalBean> mDataList = new ArrayList<ApprovalBean>();
    private ApprovalDetailAdapter mAdapter;
    private ApprovalBean ap2,ap3,ap4;
    private CloudDBOperation mCloudDBOperation;
    private ArrayList<ArrayList<DateBean>> mTimeData = new ArrayList<>();
    private ArrayList<DateBean> mSelectDate = new ArrayList<>();
    private SizeComparator mComparator;

    private String[] mDayPart = {"","上午","下午"};
    private long mOneDayTime = 24 * 60 * 60; // 一天的秒数
    private String mAppId;
    private String mRefuseReason = "";
    private String mUid;
    private int mAction;
    private int mListType;
    private int mAppType; // 申请类型, 1.出差，2.请假，3.外出，4.签到
    private String[] mTimeTitle = {"","出差时间: ","请假时间: ","外出时间: ","签到异常时间: "};

    private static final int APPROVAL_ACTION = 20001;
    private static final int APPROVAL_DETAIL = 20002;
    private static final int APPROVAL_CANCEL = 20003;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case APPROVAL_ACTION:
                    waitDlgDismiss();
                    if (msg.arg1 == 0){
                        int action = (Integer)msg.obj;
                        String uid = mApprovalData.getUser_id();
                        if (uid.equals(mUid)){
                            mTvStatus.setText("我已审批");
                        }else{
                            mTvStatus.setText(mApprovalData.getApprove_admin_name() + "已审批");
                        }
                        if (action == 1){
                            mIvStatus.setImageResource(R.drawable.approval_pass_iv);
                            mDataList.get(1).setStatus("已同意");
                            mDataList.get(1).setTime(System.currentTimeMillis() / 1000);
                        }else if (action == 2){
                            mIvStatus.setImageResource(R.drawable.approval_refause_iv);
                            mDataList.get(1).setStatus("已拒绝");
                            mDataList.get(1).setRefuseReason(mRefuseReason);
                            mDataList.get(1).setTime(System.currentTimeMillis() / 1000);
                        }else if (action == 3){
                            mIvStatus.setImageResource(R.drawable.approval_pass_iv);
                            mDataList.get(3).setStatus("已同意");
                            mDataList.get(3).setTime(System.currentTimeMillis() / 1000);
                        }else if (action == 4){
                            mIvStatus.setImageResource(R.drawable.approval_refause_iv);
                            mDataList.get(3).setStatus("已拒绝");
                            mDataList.get(3).setRefuseReason(mRefuseReason);
                            mDataList.get(3).setTime(System.currentTimeMillis() / 1000);
                        }
                        mAdapter.notifyDataSetChanged();
                        mLayoutAction.setVisibility(View.GONE);

                        if (action == 1 || action == 2){
                            mApprovalData.setApproval_status(action);
                            mApprovalData.setApproval_done_time(System.currentTimeMillis()/1000 + "");
                            mApprovalData.setApproval_refuse_reason(mRefuseReason);
                            mCloudDBOperation.upDateOneApproval(mUid,mListType,mApprovalData);
                        }else{
                            mApprovalData.setApproval_status(action - 2);
                            mApprovalData.setApproval_cancel_done_time(System.currentTimeMillis() / 1000 + "");
                            mApprovalData.setApproval_refuse_reason(mRefuseReason);
                            mCloudDBOperation.upDateCancelApproval(mUid, mListType, mApprovalData);
                        }

                    }else{
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case APPROVAL_DETAIL:
                    if (msg.arg1 == 0){
                        mApprovalData = (ApprovalData) msg.obj;
                        int status = mApprovalData.getApproval_status();
                        if (status == 0){
                            mListType = 2;
                        }else{
                            mListType = 1;
                        }
                        mLayoutContent.setVisibility(View.VISIBLE);
                        setData();
                    }
                    break;
                case APPROVAL_CANCEL:
                    waitDlgDismiss();
                    if (msg.arg1 == 0){
                        mTvStatus.setText("等待" + mApprovalData.getApprove_admin_name() + "审批");
                        mIvStatus.setVisibility(View.GONE);
                        mLayoutCancel.setVisibility(View.GONE);
                        ap3 = new ApprovalBean();
                        ap3.setImage(mApprovalData.getUser_image());
                        ap3.setName(mApprovalData.getUser_name());
                        ap3.setStatus("申请撤销");
                        ap3.setRefuseReason(mRefuseReason);
                        ap3.setTime(System.currentTimeMillis() / 1000);

                        ap4 = new ApprovalBean();
                        ap4.setImage(mApprovalData.getApprove_admin_image());
                        ap4.setName(mApprovalData.getApprove_admin_name());
                        ap4.setStatus("正在审批");

                        mDataList.add(ap3);
                        mDataList.add(ap4);
                        mAdapter.notifyDataSetChanged();
                    }else{
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle, R.layout.approval_detail_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mLayoutAgree.setOnClickListener(this);
        mLayoutRefuse.setOnClickListener(this);
        mLayoutCancel.setOnClickListener(this);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        String action = intent.getAction();
        mComparator = new SizeComparator();
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
        if ("approval".equals(action)){
            mListType = intent.getIntExtra("list_type",0);
            mApprovalData = (ApprovalData)intent.getSerializableExtra("approvalData");
            mLayoutContent.setVisibility(View.VISIBLE);
            setData();
        }else{
            mAppId = intent.getStringExtra("approval_id");
            getApprovalDetail();
        }
        mCloudDBOperation = new CloudDBOperation(mActivity);

    }

    private void setData(){

        String uid = mApprovalData.getApprove_admin();
        if (mListType == 2 && uid.equals(mUid)){
            mLayoutAction.setVisibility(View.VISIBLE);
        }
        mAppId = mApprovalData.getApproval_id();
        mAppType = mApprovalData.getApproval_type(); // 申请类型, 1.出差，2.请假，3.外出，4.签到
        switch (mAppType){
            case 1:
                mLayoutTraval.setVisibility(View.VISIBLE);
                String place = mApprovalData.getApproval_address();
                if (!StringUtil.isEmpty(place)){
                    mTvTravalPlace.setText(place);
                }
                mTvTitle.setText(R.string.approval_travel);
                mTvDayTitle.setText("出差天数: ");
                mTvReasonTitle.setText("出差事由: ");
                break;
            case 2:
                mLayoutLeaveType.setVisibility(View.VISIBLE);
                int leaveType = mApprovalData.getApproval_leave_type();
                switch (leaveType){
                    case 0:
                        mTvLeaveType.setText(getString(R.string.ap_reason_1));
                        break;
                    case 1:
                        mTvLeaveType.setText(getString(R.string.ap_reason_2));
                        break;
                    case 2:
                        mTvLeaveType.setText(getString(R.string.ap_reason_3));
                        break;
                    case 3:
                        mTvLeaveType.setText(getString(R.string.ap_reason_4));
                        break;
                    case 4:
                        mTvLeaveType.setText(getString(R.string.ap_reason_5));
                        break;
                }
                mTvTitle.setText(R.string.approval_leave);
                mTvDayTitle.setText("请假天数: ");
                mTvReasonTitle.setText("请假事由:");
                break;
            case 3:
                mTvTitle.setText(R.string.approval_out);
                mTvDayTitle.setText("外出天数: ");
                mTvReasonTitle.setText("外出事由: ");
                break;
            case 4:
                mTvTitle.setText(R.string.approval_sign);
                mLayoutEnd.setVisibility(View.GONE);
                mLayoutDays.setVisibility(View.GONE);
                mTvReasonTitle.setText("签到异常原因: ");
                mTvStartTimeTitle.setText("签到异常时间: ");
                break;
        }
        ImageLoaderInterface.imageLoader.displayImage(mApprovalData.getUser_image(),mIvAvatar,ImageLoaderInterface.optionHeadImage);
        mTvName.setText(mApprovalData.getUser_name());


        ApprovalBean ap1 = new ApprovalBean();
        ap1.setImage(mApprovalData.getUser_image());
        ap1.setName(mApprovalData.getUser_name());
        ap1.setStatus("发出申请");
        ap1.setTime(Long.parseLong(mApprovalData.getApproval_time()));

        ap2 = new ApprovalBean();
        ap2.setImage(mApprovalData.getApprove_admin_image());
        ap2.setName(mApprovalData.getApprove_admin_name());

        int status = mApprovalData.getApproval_status();
        if (status == 0){
            ap2.setStatus("审批中...");
            ap2.setTime(0l);
            if (uid.equals(mUid)){
                mTvStatus.setText("等待我审批");
            }else{
                mTvStatus.setText("等待" + mApprovalData.getApprove_admin_name() + "审批");
            }
        }else if (status == 1){
            if (uid.equals(mUid)){
                mTvStatus.setText("我已审批");
            }else{
                mTvStatus.setText(mApprovalData.getApprove_admin_name() + "已审批");
            }
            if (mListType == 1 && mApprovalData.getUser_id().equals(mUid) && mAppType != 4){
                mLayoutCancel.setVisibility(View.VISIBLE);
            }
            mIvStatus.setImageResource(R.drawable.approval_pass_iv);
            ap2.setStatus("已同意");
            ap2.setTime(Long.parseLong(mApprovalData.getApproval_done_time()));

        }else {
            if (uid.equals(mUid)){
                mTvStatus.setText("我已审批");
            }else{
                mTvStatus.setText(mApprovalData.getApprove_admin_name() + "已审批");
            }
            mIvStatus.setImageResource(R.drawable.approval_refause_iv);
            ap2.setStatus("已拒绝");
            ap2.setRefuseReason(mApprovalData.getApproval_refuse_reason());
            ap2.setTime(Long.parseLong(mApprovalData.getApproval_done_time()));

        }

        if (mApprovalData.getApproval_cancel() == 3){
            mDataList.add(ap1);
            mDataList.add(ap2);
        }else{
            mLayoutCancel.setVisibility(View.GONE);
            ap2.setStatus("已同意");
            ap2.setTime(Long.parseLong(mApprovalData.getApproval_done_time()));

            ap3 = new ApprovalBean();
            ap3.setImage(mApprovalData.getUser_image());
            ap3.setName(mApprovalData.getUser_name());
            ap3.setStatus("申请撤销");
            ap3.setRefuseReason(mApprovalData.getApproval_cancel_reason());
            if (!StringUtil.isEmpty(mApprovalData.getApproval_cancel_time())){
                ap3.setTime(Long.parseLong(mApprovalData.getApproval_cancel_time()));
            }

            ap4 = new ApprovalBean();
            if (status == 0){
                ap4.setStatus("审批中...");
            }else if (status == 1){
                ap4.setStatus("已同意");
                ap4.setTime(Long.parseLong(mApprovalData.getApproval_cancel_done_time()));
            }else if (status == 2){
                ap2.setRefuseReason("");
                ap4.setStatus("已拒绝");
                ap4.setTime(Long.parseLong(mApprovalData.getApproval_cancel_done_time()));
                ap4.setRefuseReason(mApprovalData.getApproval_refuse_reason());
            }
            ap4.setImage(mApprovalData.getApprove_admin_image());
            ap4.setName(mApprovalData.getApprove_admin_name());

            mDataList.add(ap1);
            mDataList.add(ap2);
            mDataList.add(ap3);
            mDataList.add(ap4);

        }


        String dates = mApprovalData.getApproval_dates();
        if (!StringUtil.isEmpty(dates)){
            mLayoutEnd.setVisibility(View.GONE);
            mTvStartTimeTitle.setText(mTimeTitle[mAppType]);
            try {
                JSONArray array = new JSONArray(dates);
                mSelectDate.clear();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject date = array.getJSONObject(i);
                    DateBean bean = new DateBean(date.getLong("time"),date.getInt("part"));
                    mSelectDate.add(bean);
                }
                getTime();
                mTvDays.setText(mApprovalData.getApproval_day() + "");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else{
            String approval_start_time = mApprovalData.getApproval_start_time();
            if (!StringUtil.isEmpty(approval_start_time)){
                String start = DateUtil.getApprovalTime(Long.parseLong(approval_start_time) * 1000);
                String startPart = mApprovalData.getApproval_start_part() == 1 ?" 上午":" 下午";
                mTvStartTime.setText(start + startPart);
                if (mAppType != 4){
                    String approval_end_time = mApprovalData.getApproval_end_time();
                    if (!StringUtil.isEmpty(approval_end_time)){
                        String end = DateUtil.getApprovalTime(Long.parseLong(approval_end_time) * 1000);
                        String endPart = mApprovalData.getApproval_end_part() == 1 ?" 上午":" 下午";
                        mTvEndTime.setText(end + endPart);
                        mTvDays.setText(mApprovalData.getApproval_day() + "");
                    }
                }
            }
        }

        mTvReason.setText(mApprovalData.getApproval_reason());
        mAdapter = new ApprovalDetailAdapter(mActivity,mDataList);
        mApLv.setAdapter(mAdapter);
    }

    private void getTime(){

        Collections.sort(mSelectDate, mComparator);
        mTimeData.clear();
        for (int i = 0; i < mSelectDate.size(); i++) {
            DateBean curBean = mSelectDate.get(i);
            if (i == 0){
                ArrayList<DateBean> time = new ArrayList<>();
                time.add(curBean);
                mTimeData.add(time);
            }else{
                DateBean lastBean = mSelectDate.get(i - 1);
                if ((curBean.getTime() - lastBean.getTime()) == mOneDayTime && lastBean.getPart() == 0 && curBean.getPart() == 0){
                    mTimeData.get(mTimeData.size() - 1).add(curBean);
                }else{
                    ArrayList<DateBean> time = new ArrayList<>();
                    time.add(mSelectDate.get(i));
                    mTimeData.add(time);
                }
            }
        }
        mTvStartTime.setText(setTimeShow());

    }

    private String setTimeShow(){
        StringBuilder selectTime = new StringBuilder();
        for (int i = 0; i < mTimeData.size(); i++) {
            ArrayList<DateBean> time = mTimeData.get(i);
            String str = "";
            if (time.size() > 0){
                if (time.size() == 1){
                    str =  DateUtil.getAppYandMandD(time.get(0).getTime() * 1000) + mDayPart[time.get(0).getPart()] ;
                }else{
                    long time1 = time.get(0).getTime();
                    long time2 = time.get(time.size() -1).getTime();
                    if (DateUtil.getYear(time1 * 1000) == DateUtil.getYear(time2 * 1000)){
                        str =  getAppYandMandD(time1 * 1000) + " - " + DateUtil.getAppMandD(time2 * 1000);
                    }else{
                        str =  getAppYandMandD(time1 * 1000) + " - " + getAppYandMandD(time2 * 1000);
                    }
                }
            }
            if(i == mTimeData.size() -1){
                selectTime.append(str);
            }else{
                selectTime.append(str + "\n");
            }
        }
        return selectTime.toString();

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.approval_detaill_ll_back:
                finish();
                break;
            case R.id.approval_botton_agree:
                if (Constants.isFastClick()) {
                    return;
                }
                if (mDataList.size() == 2){
                    mAction = 1;
                }else{
                    mAction = 3;
                }
                showDialogMsg(1,"是否同意" + mApprovalData.getUser_name() + "的申请?");
                break;
            case R.id.approval_botton_refuse:
                if (Constants.isFastClick()) {
                    return;
                }
                if (mDataList.size() == 2){
                    mAction = 2;
                }else{
                    mAction = 4;
                }
                showRefuseDialogMsg(2, "拒绝理由","是否拒绝" + mApprovalData.getUser_name() + "的申请?");
                break;
            case R.id.approval_botton_cancel:
                if (Constants.isFastClick()) {
                    return;
                }
                showRefuseDialogMsg(0, "撤销理由","该申请撤销后，其对应的考勤记录将一并删除，您是否确定撤销?");
                break;
        }

    }

    public void showDialogMsg(final int action,String message) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);
        mDialogUtil.titleDeleteMsgStyle("提示",okText, cancelText, message);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                waitDlgShow();
                setApprovalData(action,null);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    public void showRefuseDialogMsg(final int action,String reason,String message) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);

        mDialogUtil.approvalEditStyle("提示",reason,okText,cancelText,message);
        mDialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog, EditText ed) {
                mRefuseReason = ed.getEditableText().toString().trim();
                waitDlgShow();
                if (action == 2 ){
                    setApprovalData(action,mRefuseReason);
                }else if (action == 0){
                    cancelApproval(mRefuseReason);
                }
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog, EditText ed) {
                lDialog.dismiss();
            }
        });

    }


    /**
     * 处理审批
     */
    private void setApprovalData(int action,String reason){

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROCAL_ID, mAppId));
        nvps.add(new BasicNameValuePair("action_type", action+""));
        if (!StringUtil.isEmpty(reason)){
            nvps.add(new BasicNameValuePair("refuse_reason", reason));
        }
        Message message = mHandler.obtainMessage(APPROVAL_ACTION);
        WithoutObjMsg msg = new WithoutObjMsg(message);
        message.obj = mAction;
        msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_ACTION;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(mActivity).execEventHttp(msg);

    }

    /**
     * 撤销申请
     */
    private void cancelApproval(String reason){

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROCAL_ID, mAppId));
        if (!StringUtil.isEmpty(reason)){
            nvps.add(new BasicNameValuePair("approval_cancel_reason", reason));
        }
        Message message = mHandler.obtainMessage(APPROVAL_CANCEL);
        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(message);
        msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_CANCEL;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(mActivity).execEventHttp(msg);

    }

    /**
     * 获取详情
     */
    private void getApprovalDetail(){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROCAL_ID, mAppId));
        Message message = mHandler.obtainMessage(APPROVAL_DETAIL);
        GetApprovalDetail msg = new GetApprovalDetail(message);
        msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_DETAIL;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(mActivity).execEventHttp(msg);
    }

    /**
     *实现Comparator接口类
     */
    public class SizeComparator implements Comparator<DateBean> {
        @Override
        public int compare(DateBean arg0, DateBean arg1) {
            // jdk 1.7以后（包括1.7）返回相反数才行
            if(arg0.getTime() > arg1.getTime()){
                return 1;
            }
            return -1;
        }

    }


}
